/**
 * 内存系统相关的TypeScript类型定义
 * 从ai-writer-lite项目迁移
 */

import { Document } from "@langchain/core/documents";
import { BaseMessage } from "@langchain/core/messages";

// 基础内存接口
export interface BaseMemory {
  type: MemoryType;
  namespace: string;
  enabled: boolean;
  clear: () => Promise<void>;
  save: () => Promise<void>;
  load: () => Promise<void>;
}

// 内存类型
export type MemoryType =
  | 'conversational'
  | 'vector'
  | 'episodic'
  | 'knowledge'
  | 'working'
  | 'long-term';

// 对话内存接口
export interface ConversationalMemory extends BaseMemory {
  type: 'conversational';
  messages: BaseMessage[];
  maxMessages: number;
  returnMessages: boolean;
  addMessage: (message: BaseMessage) => Promise<void>;
  getMessages: (limit?: number) => BaseMessage[];
  searchMessages: (query: string, limit?: number) => BaseMessage[];
  deleteMessage: (messageId: string) => Promise<void>;
}

// 向量存储内存接口
export interface VectorStoreMemory extends BaseMemory {
  type: 'vector';
  documents: Document[];
  vectorStore: any; // VectorStore类型
  embeddingModel: string;
  similarityThreshold: number;
  maxDocuments: number;
  addDocument: (document: Document) => Promise<void>;
  addDocuments: (documents: Document[]) => Promise<void>;
  search: (query: string, k?: number) => Promise<Document[]>;
  deleteDocument: (documentId: string) => Promise<void>;
  updateDocument: (documentId: string, document: Document) => Promise<void>;
}

// 情节内存接口
export interface EpisodicMemory extends BaseMemory {
  type: 'episodic';
  episodes: Episode[];
  maxEpisodes: number;
  addEpisode: (episode: Episode) => Promise<void>;
  getEpisode: (episodeId: string) => Episode | undefined;
  getEpisodes: (limit?: number, filter?: EpisodeFilter) => Episode[];
  searchEpisodes: (query: string, limit?: number) => Episode[];
  deleteEpisode: (episodeId: string) => Promise<void>;
  updateEpisode: (episodeId: string, episode: Episode) => Promise<void>;
}

// 知识图谱内存接口
export interface KnowledgeGraphMemory extends BaseMemory {
  type: 'knowledge';
  nodes: KnowledgeNode[];
  edges: KnowledgeEdge[];
  addNode: (node: KnowledgeNode) => Promise<void>;
  addEdge: (edge: KnowledgeEdge) => Promise<void>;
  getNode: (nodeId: string) => KnowledgeNode | undefined;
  getEdge: (edgeId: string) => KnowledgeEdge | undefined;
  searchNodes: (query: string, limit?: number) => KnowledgeNode[];
  findRelatedNodes: (nodeId: string, maxDepth?: number) => KnowledgeNode[];
  findPath: (fromId: string, toId: string) => KnowledgeEdge[];
  deleteNode: (nodeId: string) => Promise<void>;
  deleteEdge: (edgeId: string) => Promise<void>;
}

// 情节定义
export interface Episode {
  id: string;
  timestamp: Date;
  title: string;
  description: string;
  content: string;
  context: Record<string, any>;
  importance: number;
  tags: string[];
  relatedEpisodes: string[];
  metadata: EpisodeMetadata;
}

// 情节过滤器
export interface EpisodeFilter {
  dateRange?: { start: Date; end: Date };
  tags?: string[];
  importance?: { min: number; max: number };
  context?: Record<string, any>;
}

// 情节元数据
export interface EpisodeMetadata {
  projectId?: string;
  chapterId?: string;
  taskType?: string;
  toolUsed?: string;
  userRating?: number;
  duration?: number;
  tokensUsed?: number;
}

// 知识节点定义
export interface KnowledgeNode {
  id: string;
  type: NodeType;
  label: string;
  properties: Record<string, any>;
  embedding?: number[];
  createdAt: Date;
  updatedAt: Date;
  confidence: number;
  source?: string;
}

// 节点类型
export type NodeType =
  | 'character'
  | 'location'
  | 'concept'
  | 'event'
  | 'relationship'
  | 'theme'
  | 'object'
  | 'emotion'
  | 'action'
  | 'custom';

// 知识边定义
export interface KnowledgeEdge {
  id: string;
  fromId: string;
  toId: string;
  type: EdgeType;
  weight: number;
  properties: Record<string, any>;
  createdAt: Date;
  confidence: number;
}

// 边类型
export type EdgeType =
  | 'related_to'
  | 'part_of'
  | 'located_at'
  | 'caused_by'
  | 'leads_to'
  | 'similar_to'
  | 'opposite_of'
  | 'belongs_to'
  | 'custom';

// 工作内存接口
export interface WorkingMemory extends BaseMemory {
  type: 'working';
  capacity: number;
  currentContext: Record<string, any>;
  activeTasks: ActiveTask[];
  store: (key: string, value: any) => Promise<void>;
  retrieve: (key: string) => any;
  has: (key: string) => boolean;
  clear: () => Promise<void>;
  addTask: (task: ActiveTask) => Promise<void>;
  completeTask: (taskId: string) => Promise<void>;
  getActiveTasks: () => ActiveTask[];
}

// 活跃任务定义
export interface ActiveTask {
  id: string;
  type: string;
  description: string;
  priority: number;
  status: 'pending' | 'in_progress' | 'completed' | 'failed';
  data: Record<string, any>;
  createdAt: Date;
  updatedAt: Date;
}

// 长期内存接口
export interface LongTermMemory extends BaseMemory {
  type: 'long-term';
  consolidationEnabled: boolean;
  consolidationInterval: number; // 小时
  lastConsolidation: Date;
  consolidate: () => Promise<void>;
  forget: (criteria: ForgettingCriteria) => Promise<void>;
  reinforce: (nodeIds: string[]) => Promise<void>;
}

// 遗忘标准
export interface ForgettingCriteria {
  importance?: { below: number };
  age?: { olderThan: Date };
  accessFrequency?: { lessThan: number };
  lastAccess?: { before: Date };
}

// 内存搜索参数
export interface MemorySearchParams {
  query: string;
  memoryTypes?: MemoryType[];
  limit?: number;
  threshold?: number;
  filters?: Record<string, any>;
  includeMetadata?: boolean;
}

// 内存搜索结果
export interface MemorySearchResult {
  type: MemoryType;
  id: string;
  content: string | Document | Episode | KnowledgeNode;
  relevanceScore: number;
  metadata: Record<string, any>;
}

// 内存统计信息
export interface MemoryStatistics {
  totalItems: number;
  itemsByType: Record<MemoryType, number>;
  totalSize: number; // 字节
  averageAccessTime: number;
  hitRate: number;
  lastAccess?: Date;
  growthRate: number; // 每日增长
}

// 内存配置
export interface MemoryConfig {
  conversational: {
    maxMessages: number;
    returnMessages: boolean;
    autoSave: boolean;
  };
  vector: {
    enabled: boolean;
    vectorStore: 'chroma' | 'faiss' | 'pinecone';
    embeddingModel: string;
    dimension: number;
    similarityThreshold: number;
    maxDocuments: number;
  };
  episodic: {
    enabled: boolean;
    maxEpisodes: number;
    importanceThreshold: number;
    autoConsolidation: boolean;
  };
  knowledge: {
    enabled: boolean;
    graphDatabase: 'neo4j' | 'arangoDB' | 'custom';
    nodeTypes: NodeType[];
    edgeTypes: EdgeType[];
    confidenceThreshold: number;
  };
  working: {
    capacity: number;
    autoCleanup: boolean;
    maxTaskAge: number; // 分钟
  };
  longTerm: {
    enabled: boolean;
    consolidationInterval: number;
    forgettingEnabled: boolean;
    reinforcementEnabled: boolean;
  };
}

// 内存事件类型
export type MemoryEventType =
  | 'item:added'
  | 'item:updated'
  | 'item:deleted'
  | 'item:accessed'
  | 'memory:cleared'
  | 'memory:consolidated'
  | 'memory:compressed';

// 内存事件数据
export interface MemoryEvent {
  type: MemoryEventType;
  timestamp: Date;
  memoryType: MemoryType;
  itemId?: string;
  data?: any;
  metadata?: Record<string, any>;
}

// 导出所有类型
export type {
  BaseMemory,
  MemoryType,
  ConversationalMemory,
  VectorStoreMemory,
  EpisodicMemory,
  KnowledgeGraphMemory,
  WorkingMemory,
  LongTermMemory,
  Episode,
  EpisodeFilter,
  EpisodeMetadata,
  KnowledgeNode,
  NodeType,
  KnowledgeEdge,
  EdgeType,
  ActiveTask,
  ForgettingCriteria,
  MemorySearchParams,
  MemorySearchResult,
  MemoryStatistics,
  MemoryConfig,
  MemoryEvent,
  MemoryEventType,
};